package ai.people.core.common.properties.elastic;

import ai.people.netmon.utils.StringPool;
import ai.people.netmon.utils.StringUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ES索引映射关系
 *
 * @author yuanqinglong
 * @date 2022/5/9 13:28
 */
@Component
@ConfigurationProperties(prefix = "elastic.user")
public class ElasticUserIndex {

    /**
     * 索引名称映射
     */
    private static Map<String, String> indexMapping = new HashMap<>();

    /**
     * 索引映射
     */
    private static List<IndexInfo> indexType;

    /**
     * 配置未传信源名称、默认全部索引名称
     */
    private static String allIndex;


    @PostConstruct
    private void init() {
        allIndex = Optional.ofNullable(allIndex).orElse("user-*");
        indexMapping = Optional.ofNullable(indexType).map(indexInfos -> indexType.stream().collect(Collectors.toMap(IndexInfo::getSourceName, IndexInfo::getIndexName, (s, s2) -> s2)))
                .orElseGet(HashMap::new);
    }


    /**
     * 得到索引名称
     *
     * @param sourceName 源名称
     * @return {@link String}
     */
    public static String getIndexName(String sourceName) {
        if (StringUtils.isNotEmpty(sourceName)) {
            Set<String> sources = Arrays.stream(sourceName.split(StringPool.COMMA)).collect(Collectors.toSet());
            List<String> filterSources = sources.stream().filter(name -> indexMapping.containsKey(name)).map(source -> indexMapping.get(source)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(filterSources)){
                return null;
            }
            return StringPool.SLASH + String.join(StringPool.COMMA, filterSources);
        }
        return StringPool.SLASH + indexMapping.getOrDefault(sourceName, allIndex);
    }


    public static String getOriginIndexName(String sourceName){
        return StringUtils.isNotEmpty(sourceName) ? indexMapping.get(sourceName) : allIndex;
    }


    public void setIndexType(List<IndexInfo> index) {
        ElasticUserIndex.indexType = index;
    }

    public void setAllIndex(String allIndex) {
        ElasticUserIndex.allIndex = allIndex;
    }

    @Data
    static class IndexInfo {
        /**
         * 源名称
         */
        private String sourceName;
        /**
         * 索引名称
         */
        private String indexName;
    }

    /**
     * 得到所有信源名称
     *
     * @return {@link List}<{@link String}>
     */
    public List<String> getAllInformationSourceNames(){
        return indexType.stream().map(IndexInfo::getSourceName).collect(Collectors.toList());
    }

    public static String getAllIndex() {
        return allIndex;
    }
}
